﻿using System.Collections.Generic;
using Core;
using UnityEngine;

namespace Modules.UI.Sub
{
    public class SubCanvas : GameSubsystem
    {
        private const string StoreName = "SubPageStore";
        private readonly List<SubPage> _contentPages = new List<SubPage>();
        private SubPageStore _pageStore;
        private Canvas _canvas;

        protected override void Awake()
        {
            base.Awake();
            _canvas = GetComponent<UnityEngine.Canvas>();
            _pageStore = Resources.Load<SubPageStore>(StoreName);
        }

        public SubPage LoadPage(string pageName)
        {
            SubPage tempPage = _pageStore.Get(pageName);
            SubPage page = (SubPage)Instantiate(tempPage, transform);
            _contentPages.Add(page);
            return page;
        }

        public void UnloadPage(SubPage page)
        {
            if (_contentPages.Remove(page))
            {
                Destroy(page.gameObject);
            }
        }

        public Vector3 GetWorldPosition(Vector2 screenPosition)
        {
            RectTransformUtility.ScreenPointToWorldPointInRectangle(_canvas.transform as RectTransform, screenPosition, _canvas.worldCamera, out Vector3 worldPosition);
            return worldPosition;
        }

        public Vector2 GetScreenPosition(Vector3 worldPosition)
        {
            return RectTransformUtility.WorldToScreenPoint(_canvas.worldCamera, worldPosition);
        }


        public float Distance => _canvas.planeDistance;
    }
}